import { history } from 'umi';
import api from 'api';
import { pathToRegexp } from 'path-to-regexp'

const { GetSystemTimeAPI } = api

export default {
    namespace: 'user',
    state: {
        userInfo: {
            userId: -1,
            account: "",
            displayName: "",
            signature: "",
            imgFileId: 2,
            userType: -1,
            status: 0,
            realName: "",
            school: "",
            college: "",
            class: "",
            follow: 0,
            followed: 0,
            createTime: "",
            imgFileName: "",
            imgFilePath: ""
        },
        accessToken: "",
        refreshToken: "",
        pathname: "",
    },
    subscriptions: {
        // 只在第一次访问或者刷新浏览器时才触发此函数
        setup({ history, dispatch }, error) {
            history.listen(({ pathname, state }) => {
                // console.log("用户切换路径", pathname);
                dispatch({ type: "updatePathname", payload: pathname });
            });
            // console.log("查询用户信息");
            dispatch({ type: 'query', payload: history.location.pathname });
        },
    },
    effects: {
        *query({ payload }, { select, put }) {
            try {
                let userInfo = null;
                // 先从localStorage获取userInfo
                const userInfoStr = window.localStorage.getItem("hudazx-blog-userInfo");
                const accessToken = window.localStorage.getItem("hudazx-blog-accessToken");
                const refreshToken = window.localStorage.getItem("hudazx-blog-refreshToken");


                if (userInfoStr && accessToken && refreshToken) {
                    userInfo = JSON.parse(userInfoStr, userInfo);
                    //这里在重复刷新的时候，会读取缓存值，而state中值并未改变
                    yield put({ type: "syncUser", payload: { userInfo: userInfo, accessToken: accessToken, refreshToken: refreshToken } });
                }
                else {
                    // 或从state里获取userInfo
                    userInfo = yield select(_ => _.user.userInfo);
                }
                // 用户无论是否登陆都可以查看文章
                if (payload === "/") {
                    history.push({ pathname: '/homePage' });
                }

            } catch (error) {
                console.error("用户信息查询出错：" + error);
            }
        },

        *logout({ }, { put }) {
            yield put({ type: "logoutUser" });
            history.push({ pathname: '/homePage' });
        },

        *querySystemTime({ callback }, { call, put }) {
            const result = yield call(GetSystemTimeAPI);
            if (result.success) {
                const sysTime = result.data.replace(/\-/g, "/");
                const sysDate = new Date(sysTime);
                // const cDate = new Date();
                // if (Math.abs(parseInt(sysDate - cDate)) > 60000) {
                // yield put({ type: 'updateState', payload: { offsetTime: parseInt(sysDate - cDate) } });
                // }
                callback(sysDate);
            }
        },
    },
    reducers: {
        updateUser(state, { payload }) {
            // 将user信息存入localStorage
            window.localStorage.setItem("hudazx-blog-userInfo", JSON.stringify(payload.userInfo));

            if (payload.accessToken) {
                window.localStorage.setItem("hudazx-blog-accessToken", payload.accessToken);
            }
            if (payload.refreshToken) {
                window.localStorage.setItem("hudazx-blog-refreshToken", payload.refreshToken);
            }
            return {
                ...state,
                ...payload
            }
        },
        logoutUser(state, { }) {
            //退出登录时，清空state和storage
            const initInfo = {
                userInfo: {
                    userId: -1,
                    account: "",
                    displayName: "",
                    signature: "",
                    imgFileId: 2,
                    userType: -1,
                    status: 0,
                    realName: "",
                    school: "",
                    college: "",
                    class: "",
                    follow: 0,
                    followed: 0,
                    createTime: "",
                    imgFileName: "",
                    imgFilePath: ""
                },
                accessToken: "",
                refreshToken: ""
            };
            window.localStorage.setItem("hudazx-blog-userInfo", JSON.stringify(initInfo.userInfo));
            window.localStorage.setItem("hudazx-blog-accessToken", initInfo.accessToken);
            window.localStorage.setItem("hudazx-blog-refreshToken", initInfo.refreshToken);
            window.localStorage.setItem("hudazx-blog-faceVerifyInfo", JSON.stringify(initInfo.faceVerifyInfo))
            return {
                ...state,
                ...initInfo
            }
        },
        syncUser(state, { payload }) {
            //将读到的登录用户信息，写回到state中
            return {
                ...state,
                ...payload
            }
        },
        updatePathname(state, { payload: pathname }) {
            return {
                ...state,
                pathname
            }
        },
        updateDeviceStatus(state, { payload: devicestatus }) {
            return {
                ...state,
                devicestatus: {
                    facestatus: devicestatus.FaceVerify,
                    midistatus: devicestatus.MidiFlag
                },

            }
        },
        updateFaceVerified(state, { payload: faceVerifyInfo }) {
            window.localStorage.setItem("faceVerifyInfo", JSON.stringify(faceVerifyInfo));
            return {
                ...state,
                faceVerifyInfo,
            }
        },
    }
}